package com.minimalist.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域配置
 * 
 * @author minimalist
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有请求方法
        config.addAllowedMethod("*");
        // 允许所有来源
        config.addAllowedOriginPattern("*");
        // 允许携带Cookie
        config.setAllowCredentials(true);
        // 为SSE连接添加特定的暴露头
        config.addExposedHeader("Cache-Control");
        config.addExposedHeader("Content-Type");
        config.addExposedHeader("Date");
        config.addExposedHeader("Etag");
        config.addExposedHeader("Expires");
        config.addExposedHeader("Last-Modified");
        config.addExposedHeader("Server");
        config.addExposedHeader("Transfer-Encoding");
        // 设置预检请求的缓存时间
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}